<?php
/**
 * News page controller
 *
 * @author Dima
 *
 */

class AddressController extends modules_default_controllers_ControllerUserarea
{
	public $ajaxable = array(
		'delete' => array('json')
	);

	//----------------------------------------------------------------------------------------------------

	public function init()
	{
		if (! $this->getRequest()->isXmlHttpRequest())
		{
			$this->view->title = 'Address Book';
			parent::init();

			$this->view->headLink()->appendStylesheet('/css/jquery.alerts.css');


			$this->view->headScript()->appendFile('/js/jquery.metadata.js');
			$this->view->headScript()->appendFile('/js/jquery.alerts.js');

		}

		$this->_helper->AjaxContext()->initContext('json');
	}

//----------------------------------------------------------------------------------------------------

	public function indexAction()
	{
		$allItems = models_AddressMapper::findByUserId(Lemar_User::getLoggedUserId());
		$this->view->allItems = $allItems;
	}

//----------------------------------------------------------------------------------------------------

	public function setAction()
	{
		$card = (int)$this->_getParam('card', 0);
		$page = (int)$this->_getParam('page', 1);
		$idAddress = (int)$this->_getParam('address', 0);

		$orderItem = models_OrderItemMapper::findById($card);

		if (null == $orderItem)
		{
			throw new Zend_Controller_Action_Exception('This page dont exist', 404);
		}

		$order = models_OrderMapper::findById($orderItem->idOrder);

		if (null == $order || $order->idUser != Lemar_User::getLoggedUserId())
		{
			throw new Zend_Controller_Action_Exception('This page dont exist', 404);
		}

		if (0 != $idAddress)
		{
			$address = models_AddressMapper::findById($idAddress);
			if (null == $address || $address->idUser != Lemar_User::getLoggedUserId())
			{
				throw new Zend_Controller_Action_Exception('This page dont exist', 404);
			}
			else
			{
				models_OrderItemMapper::update($card, array('address_id' => $idAddress), 'models_DbTable_OrderItem');
				$this->_redirect('/cart/');
			}
		}

		$allItems = models_AddressMapper::getAll($page, 99999);
		$this->view->idOrderItem = $orderItem->id;
		$this->view->allItems = $allItems['paginator'];
	}

//----------------------------------------------------------------------------------------------------

	public function editAction()
	{
		$idAddress = (int)$this->_getParam('id', 0);
		$address = models_AddressMapper::findById($idAddress);

		if (null != $address && $address->idUser != Lemar_User::getLoggedUserId())
		{
			throw new Zend_Controller_Action_Exception('This page dont exist', 404);
		}

		if (null == $address)
		{
			$address = new models_Address();
			$address->idUser = Lemar_User::getLoggedUserId();
		}

		$oRequest = $this->getRequest();

		if ($oRequest->isPost())
		{
			$oForm = new modules_default_forms_AddressForm();

			$address->title = $oRequest->getParam('title');
			$address->firstName = $oRequest->getParam('first_name');
			$address->lastName = $oRequest->getParam('last_name');
			$address->company = $oRequest->getParam('company');
			$address->address = $oRequest->getParam('address');
			$address->city = $oRequest->getParam('city');
			$address->zip = $oRequest->getParam('zip');
			$address->country = $oRequest->getParam('country');

			if ($oForm->isValid($oRequest->getParams()))
			{
				$address->title = $oForm->getValue('title');
				$address->firstName = $oForm->getValue('first_name');
				$address->lastName = $oForm->getValue('last_name');
				$address->company = $oForm->getValue('company');
				$address->address = $oForm->getValue('address');
				$address->city = $oForm->getValue('city');
				$address->zip = $oForm->getValue('zip');
				$address->country = $oForm->getValue('country');

				$address->isBfpo = $oForm->getValue('is_bfpo');
				$address->service = $oForm->getValue('service');
				$address->rank = $oForm->getValue('rank');
				$address->unit = $oForm->getValue('unit');
				$address->operation = $oForm->getValue('operation');
				$address->bfpo = $oForm->getValue('bfpo');

				if ($address->id)
				{
				models_AddressMapper::update($address->id, array(
						'title' => $address->title,
						'first_name' => $address->firstName,
						'last_name' => $address->lastName,
						'company' => $address->company,
						'address' => $address->address,
						'city' => $address->city,
						'zip' => $address->zip,
						'country' => $address->country,

						'is_bfpo' => $address->isBfpo,
						'service' => $address->service,
						'rank' => $address->rank,
						'unit' => $address->unit,
						'operation' => $address->operation,
						'bfpo' => $address->bfpo,
					), 'models_DbTable_Address');
				}
				else
				{
					$newId = models_AddressMapper::save(array(
						'id' => $address->id,
						'user_id' => $address->idUser,
						'title' => $address->title,
						'first_name' => $address->firstName,
						'last_name' => $address->lastName,
						'company' => $address->company,
						'address' => $address->address,
						'city' => $address->city,
						'zip' => $address->zip,
						'country' => $address->country
					));

					$this->_redirect('/address/');
				}

				$mlId = (int)$this->_getParam('returntoml', 0);
				if (0 != $mlId)
				{
					$this->_redirect('/mailinglist/view/id/' . $mlId);
				}

			}
			else
			{

				$aValues 	= $oRequest->getParams();
				$this->view->aValues = $aValues;

				$aErrors 	= $oForm->getErrors();
				$aMessages  = $oForm->getMessages();

				$aErrorMessages = array();

				foreach ($aErrors as $sControlName => $sErrorIndexes)
				{
					foreach($sErrorIndexes as $ErrorName)
					{
						$aErrorMessages[$sControlName][$ErrorName] = $aMessages[$sControlName][$ErrorName] ;
					}
				}
				$this->view->aError = $aErrorMessages;
				$this->view->aValues = $aValues;
			}
		}
		else
		{
//			die('else');
			//$this->view->findBy = models_FindByMapper::fetchAll();
		}

		$this->view->address = $address;
	}

//----------------------------------------------------------------------------------------------------

	public function deleteAction()
	{
		$ids = $this->_getParam('id', array());

		$rids = array();

		foreach ($ids as $item)
		{
			$address = models_AddressMapper::findById($item);
			if (Lemar_User::getLoggedUserId() == $address->idUser)
			{
				try
				{
					models_AddressMapper::deleteFromBase($item, 'models_DbTable_Address');
					$rids[] = $item;
				}
				catch (Exception $e)
				{

				}
			}
		}

		$this->view->ret = 1;
		$this->view->ids = $rids;
	}

//---------------------------------------------------------------------------------------------------------------------------

	public function importAction()
	{
		$oRequest = $this->getRequest();
		if ($oRequest->isPost())
		{
			if ('' != $_FILES['myfile']['name'])
			{
				$userFile 	= $_FILES['myfile'];
				$tmpFile 	= $userFile['tmp_name'];
				$nameFile 	= $userFile['name'];

				$JobDir = $_SERVER['DOCUMENT_ROOT'] . '/i/address';
				if( ! file_exists($JobDir))
				{
					mkdir($JobDir) or die('not mkdir 579');
					chmod($JobDir, octdec('0777'));
				}

				if(rename($tmpFile, $JobDir . '/' . $nameFile))
				{
					$wfile = $JobDir . '/' . $nameFile;
					chmod($wfile, octdec('0777'));

					$data = new Lemar_SpreadsheetExcelReader();
					$data->read($wfile);

					$page = 0;
					foreach($data->sheets as $sheet)
					{
						$row = 1;
						if (isset($sheet['cells']))
						{
							foreach ($sheet['cells'] as $data)
							{
								if (1 == $row)
								{
									$head = $data;
								}
								else
								{
									for($i = 1; $i <= sizeof($head); $i++)
									{
										$dd = '';
										if( isset($data[$i]))
											$dd = $data[$i];

								  		$datas[$row][$head[$i]] = $dd;
									}
								}
								$row++;
							}
						}
						$page++;
					}
					if (isset($datas))
					$this->view->datas = $datas;
				}
				else
				{
					die('not rename');
				}
			}
		}
	}

//---------------------------------------------------------------------------------------------------------------------------

	public function importdoAction()
	{
		$oRequest 		= $this->getRequest();
		$rowName		= $oRequest->getParam('th');
		$allValue		= $oRequest->getParam('val');
		$aSave = array('user_id'	=> Lemar_User::getLoggedUserId());
		foreach ($allValue as $category => $aData0)
		{
			foreach ($aData0 as $k => $v)
			{
				$aSave[$rowName[$k]] = $v;
			}
			try {
				$ii = models_AddressMapper::saveArray($aSave, 'models_DbTable_Address');

			} catch (Exception $e) {
			}
		}
		$this->_redirect('/address');
	}

//---------------------------------------------------------------------------------------------------------------------------

	private static function HeaderingExcel($filename)
	{
		header("Content-type: application/vnd.ms-excel");
      	header("Content-Disposition: attachment; filename=$filename" );
      	header("Expires: 0");
      	header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
      	header("Pragma: public");
	}

//---------------------------------------------------------------------------------------------------------------------------

	public function exportAction()
	{

		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

		$allAB = models_AddressMapper::getAll(1, 99999999, Lemar_User::getLoggedUserId());

		self::HeaderingExcel('myExport.xls');

		$workbook = new Lemar_Workbook("-");
		$worksheet1 =& $workbook->add_worksheet('Address Book');

		$formatot =& $workbook->add_format();
		$formatot->set_size(10);
		$formatot->set_align('center');
		$formatot->set_color('white');
		$formatot->set_pattern();
		$formatot->set_fg_color('blue');

		$worksheet1->set_column(0,16,10);


		$aTh = array(	'Title', 	'Firstname', 	'Lastname', 'Company',
						'Address', 	'Town', 		'Country', 	'Postcode',
						'Birthday', 'Anniversary', 	'Custom1',
						'Custom2', 	'Custom3', 		'Custom4', 	'Custom5',
  			);
	  	$i = 0;
		foreach ($aTh as $th)
		{
	  		$worksheet1->write_string(0, $i++, $th, $formatot);
		}

		$i = 0;
		foreach ($allAB['array'] as $add)
		{
			$add = Lemar_Basic::ArrayToObject($add);
//			print_r($add);
			$i++;
			$worksheet1->write($i, 0, $add->title);
			$worksheet1->write($i, 1, $add->first_name);
			$worksheet1->write($i, 2, $add->last_name);
			$worksheet1->write($i, 3, $add->company);
			$worksheet1->write($i, 4, $add->address);
			$worksheet1->write($i, 5, $add->city);
			$worksheet1->write($i, 6, $add->country);
			$worksheet1->write($i, 7, $add->zip);
			$worksheet1->write($i, 8, $add->birthday);
			$worksheet1->write($i, 9, $add->anniversary);
		}

		$workbook->close();

	}

//---------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------------------
}